const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    "isManager": 1,
    "version": "1.0.0"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this
    if(options.openId != null){
      wx.setStorageSync('relatedOpenId', options.openId);
    }
    var nickName = wx.getStorageSync('nickName');
    var avatarUrl = wx.getStorageSync('avatarUrl');
    var isManager = wx.getStorageSync('isManager');
    var openId = wx.getStorageSync('openId');
    _this.setData({
      nickName: nickName,
      avatarUrl: avatarUrl,
      isManager: isManager,
      openId: openId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var _this = this
    var nickName = wx.getStorageSync('nickName');
    var avatarUrl = wx.getStorageSync('avatarUrl');
    var isManager = wx.getStorageSync('isManager');
    var openId = wx.getStorageSync('openId');
    _this.setData({
      nickName: nickName,
      avatarUrl: avatarUrl,
      isManager: isManager,
      openId: openId
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var openId = wx.getStorageSync('openId');
    return {
      title: '邀请好友',
      path: '/pages/user/index?openId=' + openId
    }
  },

  /**
   * 管理者入口
   */
  goadmin() {
    wx.navigateTo({
      url: '/pages/user/manager/manager',
    })
  },

  /**
   * 如果没有此用户，新增一个
   * @param {获取的openId} openId 
   */
  addUser(openId, avatarUrl){
    var _this = this;
    var relatedOpenId = wx.getStorageSync('relatedOpenId');
    app.request('/user/add', 'POST', {
      openId: openId,
      relatedOpenId: relatedOpenId,
      avatarUrl: avatarUrl
    }).then(data => {
      _this.setData({
        nickName: data.user.nickName,
        isManager: data.user.isManager,
        avatarUrl: data.user.avatarUrl
      })
      wx.setStorageSync('nickName', data.user.nickName);
      wx.setStorageSync('isManager', data.user.isManager);
      wx.setStorageSync('avatarUrl', data.user.avatarUrl);
      wx.setStorageSync('openId', openId);
      wx.showToast({
        title: '登录成功',
        icon: 'none' 
      })
    }).catch(err => {
      console.error('登录失败', err);
    });
  },

  /**
   * 调用wx接口获取code
   */
  wxLogin(avatarUrl){
    var _this = this;
    wx.login({
      success(res) { 
        _this.login(res.code, avatarUrl);
      }, 
      fail() {
        wx.showToast({
          title: '获取code失败',
          icon: 'none'
        })
        return resolve('获取code失败')
      }
    })
  },

  /**
   * 调用自己服务获取微信信息
   * @param {微信接口获取的code} code 
   */
  login(code, avatarUrl){
    var appid = app.globalData.appid;
    var _this = this;
    app.request('/wx/user/'+appid+'/login', 'GET', {
      code: code
    }).then(data => {
      _this.setData({
        openId: data.session.openid
      })
      if(data.user == null){
        _this.addUser(data.session.openid, avatarUrl);
      }else{
        _this.setData({
          nickName: data.user.nickName,
          isManager: data.user.isManager,
          avatarUrl: data.user.avatarUrl
        })
        wx.setStorageSync('nickName', data.user.nickName);
        wx.setStorageSync('avatarUrl', data.user.avatarUrl);
        wx.setStorageSync('isManager', data.user.isManager);
        wx.setStorageSync('openId', data.session.openid);
      }
    }).catch(err => {
      console.error('登录失败', err);
    });
  },

  /**
   * 
   */
  updateUserInfo(e){
    var _this = this;
    var baseUrl = app.API_BASE_URL;
    wx.uploadFile({
      url: baseUrl + '/file/upload', // 你的后端上传接口
      filePath: e.detail.avatarUrl,
      name: 'file', // 必须和后端参数名一致
      formData: {
        // 如果需要额外参数可在这里传递
      },
      success(res) {
        var data = JSON.parse(res.data);
        _this.wxLogin(app.getFileUrl(data.file));
      },
      fail(err) {
        console.error(err)
        wx.showToast({
          title: '上传失败: ' + (err.errMsg || JSON.stringify(err)),
          icon: 'error',
          duration: 3000
        });
        // 复制到剪贴板
        wx.setClipboardData({
          data: (err.errMsg || JSON.stringify(err)),
          success() {
            console.log('错误信息已复制到剪贴板');
          }
        });
      }
    })
    
  },

  logout(){
    this.setData({
      openId: null,
      nickName: null,
      avatarUrl: null,
      isManager: null,
    })
    wx.clearStorageSync()
  },

  // 判断是否登录
  checkLogin() {
    const openId = wx.getStorageSync('openId');
    if (!openId) {
      this.updateUserInfo()
    }
    return true;
  },

  // 我的订单
  goOrder() {
    if (!this.checkLogin()) return;
    wx.navigateTo({
      url: '/pages/user/order/order'
    });
  },

  // 优惠券
  goCoupon() {
    if (!this.checkLogin()) return;
    wx.navigateTo({
      url: '/pages/user/coupon/coupon'
    });
  }
})